import api from "../../api/index.js";
const app = getApp();
Page({
  offsetTopList: [],
  lastScrollTop: 0,
  data: {
    sideBarIndex: 0,
    scrollTop: 0,
    navbarHeight: 0,
    goodsTypes: [], //商品数据
    myShoppingCart: {},
    visibleGoodsSpecPop: false,
    currentGoods: {}
  },
  async onLoad() {
    this.setData({
      myShoppingCart: getApp().globalData.shopCart
    })
    await this.initData() //初始化数据
    //订阅购物车变动事件 TODO
    const _this = this
    app.eventShopBus.on("update", (shopCart) => {
      _this.setData({
        myShoppingCart: shopCart
      })
    })
    const query = wx.createSelectorQuery().in(this);
    const {
      sideBarIndex
    } = this.data;
    query.selectAll('.title').boundingClientRect();
    query.select('.custom-navbar').boundingClientRect();
    query.exec((res) => {
      const [rects, {
        height: navbarHeight
      }] = res;
      this.offsetTopList = rects.map((item) => item.top - navbarHeight);
      this.setData({
        navbarHeight,
        scrollTop: this.offsetTopList[sideBarIndex]
      });
    });
  },
  async initData() {
    const res = await api.goodsForOrder({
      method: "get"
    });
    this.setData({
      goodsTypes: res.data
    })

  },
  onSideBarChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      sideBarIndex: value,
      scrollTop: this.offsetTopList[value]
    });
  },
  onScroll(e) {
    const {
      scrollTop
    } = e.detail;
    const threshold = 50; // 下一个标题与顶部的距离
    const direction = scrollTop > this.lastScrollTop ? 'down' : 'up';
    this.lastScrollTop = scrollTop;

    // 动态调整阈值：向下滚动时增大阈值，向上时减小
    const dynamicThreshold = direction === 'down' ? threshold * 1.5 : threshold * 0.8;

    // 使用二分查找优化查找效率
    const findNearestIndex = (arr, target) => {
      let left = 0;
      let right = arr.length - 1;
      let result = 0;
      while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (arr[mid] <= target + dynamicThreshold) {
          result = mid;
          left = mid + 1;
        } else {
          right = mid - 1;
        }
      }
      return result;
    };

    const newIndex = findNearestIndex(this.offsetTopList, scrollTop);

    if (newIndex !== this.data.sideBarIndex) {
      this.setData({
        sideBarIndex: newIndex
      });
    }
  },
  onSubFromCart(e) {
    const {
      value,
      item
    } = e.detail;
    //兼容多规格
    let shop = getApp().globalData.shopCart;
    if (shop.goodsList[item.id] && Object.keys(shop.goodsList[item.id].goodsIdNames).length > 1) {
      //选择弹框
      this.toSelectSpec(e)
      return
    }
    if (shop.goodsList[item.id]) {
      item.goodsName = Object.keys(shop.goodsList[item.id].goodsIdNames)[0] //商品名
    }
    //发布购物车更新事件
    this.emitUpdateShopBus({
      id: item.id,
      name: item.goodsName,
      num: value,
      unitPrice: item.price
    })
  },
  onAddToCart(e) {
    const {
      value,
      item
    } = e.detail;
    //兼容多规格
    let shop = getApp().globalData.shopCart;
    if (shop.goodsList[item.id] && Object.keys(shop.goodsList[item.id].goodsIdNames).length > 1) {
      //选择弹框
      this.toSelectSpec(e)
      return
    }
    if (shop.goodsList[item.id]) {
      item.goodsName = Object.keys(shop.goodsList[item.id].goodsIdNames)[0] //商品名
    }

    this.emitUpdateShopBus({
      id: item.id,
      name: item.goodsName,
      num: value,
      unitPrice: item.price
    })
  },
  emitUpdateShopBus(newGoods) {
    app.eventShopBus.emit("update", newGoods)
  },
  onCheckout() {
    wx.navigateTo({
      url: '/pages/order-confirm/index?modalType=1',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('couponList', {
          data: 'test'
        })
      }
    })
  },
  onDetails(e) {
    this.toSelectSpec(e)
  },
  //---------------------商品规格详情弹框---------------------------------------------------
  toSelectSpec(e) {
    const {
      item
    } = e.detail;
    this.data.currentGoods = item;
    this.setData({
      currentGoods: item,
      visibleGoodsSpecPop: true
    });
  },
  popCanceCard() {
    this.setData({
      visibleGoodsSpecPop: false
    });
  },
  popAddCard() {
    this.setData({
      visibleGoodsSpecPop: false
    });
  }
});